<?php

namespace control;

/*
*生产派工单类
*/

class machiningSendOrderClass extends adIndexClass
{
	private const table = 'machining_send_order';
	private const page  = 'machiningSendOrder';
	private const title = '生产派工单';
	private array $typeOption      = ['生产加工', '生产返工'];
	public array  $stateOption     = ['草稿', '待确认', '已确认'];
	private array $orderTypeOption = ['生产计划' => '生产计划单', '半成品' => '半成品加工单'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'partReportSearch':
            case 'reportedSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => "加工单类型",
                        'width' => 150,
                    ],
                    'tags'          => [
                        'name'  => "单据标签",
                        'width' => 150,
                    ],
                    'line'          => [
                        'name'  => "生产线",
                        'width' => 200,
                    ],
                    'process'          => [
                        'name'  => "工序",
                        'width' => 150,
                    ],
                    'team'          => [
                        'name'  => "班组",
                        'width' => 150,
                    ],
                    'code'  => [
                        'name'  => '物料编码',
                        'width' => 150,
                    ],
                    'name'         => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'num'          => [
                        'name'  => '派工数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'reportNum'          => [
                        'name'  => '已报工数量',
                        'width' => 100,
                    ],
                    'equipment'          => [
                        'name'  => '关联设备',
                        'width' => 120,
                    ],
                    'orderType'          => [
                        'name'  => '源单类型',
                        'width' => 100,
                    ],
                    'sourceNo'          => [
                        'name'  => '关联源单',
                        'width' => 100,
                    ],
                    'startDate'          => [
                        'name'  => '计划开工日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'endDate'          => [
                        'name'  => '计划完工时间',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 120,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => "加工单类型",
                        'width' => 150,
                    ],
                    'tags'          => [
                        'name'  => "单据标签",
                        'width' => 150,
                    ],
                    'line'          => [
                        'name'  => "生产线",
                        'width' => 200,
                    ],
                    'process'          => [
                        'name'  => "工序",
                        'width' => 150,
                    ],
                    'team'          => [
                        'name'  => "班组",
                        'width' => 150,
                    ],
                    'code'  => [
                        'name'  => '物料编码',
                        'width' => 150,
                    ],
                    'name'         => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'num'          => [
                        'name'  => '派工数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'equipment'          => [
                        'name'  => '关联设备',
                        'width' => 120,
                    ],
                    'orderType'          => [
                        'name'  => '源单类型',
                        'width' => 100,
                    ],
                    'sourceNo'          => [
                        'name'  => '关联源单',
                        'width' => 100,
                    ],
                    'startDate'          => [
                        'name'  => '计划开工日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'endDate'          => [
                        'name'  => '计划完工时间',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

	/**
	 * 查询表单
	 *
	 * @param string $workFlow
	 * @return string
	 */
	public function homeForm(string $workFlow = '草稿'): string
	{
		$array = [
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "派工单类型"   => select(array('name' => 'type', 'option' => $this->typeOption)),
                    '关联源单' => text(array('name' => 'machiningOrderNo')),
                ],
                [
                    '生产线'  => selectMultiple(array("name" => "lineId", "table" => "product_line", 'where' => "coid = '" . self::$coid . "'", 'field' => "concat(workshop,'-',name) as name,id", 'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                    "工序" => selectMultiple(array("name" => "processId", "table" => "process", 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                    '物料编码' => text(array('name' => 'code')),
                ],
                [
                    '物料名称' => text(array('name' => 'materialName')),
                    '计划开工日期' => text(array("name" => "startTime", 'laydate' => ['range' => '~'])),
                    '计划完工日期' => text(array("name" => "endTime", 'laydate' => ['range' => '~'])),
                ]
            ]
        ];
		return $this->tableShow($array,1) . $this->homeJs();
	}

	public function homeJs()
	{
		return <<<eof
<script>
function get_list_box(formName) {
    let arr = [];
    $("[name='" + formName + "'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        var vals = arr.join(",");
        window.open(root+'control/adIndex.html?cla=machiningSendOrder&fun=printEdit&listId='+vals)
    } else {
        msg('请选择需要数据');
    }
}
</script>
eof;
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm();
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*行政人事-出差记录-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url      = root . "control/adIndex.html?cla=" . $this->get('cla');
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n
                        <span onclick=\"layer('" . self::page . "','batchSend',{})\" class='spanButton'>批量派工</span>\n";
        }
        if ($this->power(self::page, "confirm")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchConfirm',{})\" class='spanButton'>批量确认</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"get_list_box('listForm')\" class='spanButton'>批量打印</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchAddTags',{formName:'listForm'})\" class='spanButton'>批量打标签</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if (optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard') {
            $button = "<span class='pageHint red left'>当前是【生产流转卡】流程</span>";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*行政人事-出差记录-查询结果*/
	public function homeSearch()
	{
		//全等查询数组
		$equal = array(
			'coid'      => self::$coid,
			"type"      => $this->post('type'),
			"processId" => $this->post('processId'),
			"lineId"    => $this->post('lineId'),
			'classify'  => '生产派工',
		);
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//单据编号
		);

		//初始化
		$and  = " and state !='已确认'";
		$mAnd = '';

		if ($this->post('machiningOrderNo')) {
			$and .= " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
		}
		if ($this->post('code')) {
			$mAnd .= " and code like '%" . $this->post('code') . "%'";
		}
		if ($this->post('materialName')) {
			$mAnd .= " and name like '%" . $this->post('materialName') . "%'";
		}
		if ($mAnd) {
			$and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
		}
		if ($this->post('startTime')) {
			$and .= self::timeComparison($this->post('startTime'), field: 'startDate');
		}
		if ($this->post('endTime')) {
			$and .= self::timeComparison($this->post('endTime'), field: 'endDate');
		}
		if ($this->post('state')) {
			$and .= " and state in ('" . implode("','", $this->post('state')) . "')";
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array(
		    "table" => self::table,
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		$url      = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate       = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"edit"   => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
				'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产派工单&id=" . $array['id'] . "')"),
			);
			$material       = query('material', "id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'tags':
                        $tags           = orderTagClass::getTagName($array['id']);
                        $row[] = $tags;
                        break;
                    case 'line':
                        $line           = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['workshop'] . '-' . $line['name'];
                        break;
                    case 'process':
                        $process        = query('process', "id = '$array[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'team':
                        $team           = query('team', "id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'equipment':
                        $row[] = equipmentClass::getName($array['deviceId']);
                        break;
                    case 'orderType':
                        $row[] = $this->orderTypeOption[$array['orderType']];
                        break;
                    case 'sourceNo':
                        $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
                        $row[] = $machiningOrder['orderNo'];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function waitReportOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm();
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	public function waitReport(): bool|string
	{
        $html = $this->waitReportOptions(false);
        //控件
        $button = "";
        if ($this->power('machiningSendOrderWaitReport', "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','batchReport',$('form[name=waitReport]').serialize())\" class='spanButton'>批量报工</span>\n
                        ";//<span onclick=\"layer('" . self::page . "','outsource',{})\" class='spanButton'>工序委外</span>\n
        }
        if ($this->power('machiningSendOrderWaitReport', "print")) {
            $button .= "<span onclick=\"get_list_box('waitReport')\" class='spanButton'>批量打印</span>\n";
        }
        if ($this->power('machiningSendOrderWaitReport', "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','batchAddTags',{formName:'waitReport'})\" class='spanButton'>批量打标签</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	public function waitReportSearch(): bool|string
	{
		//全等查询数组
		$equal = array(
			'coid'      => self::$coid,
			"type"      => $this->post('type'),
			"processId" => $this->post('processId'),
			"lineId"    => $this->post('lineId'),
			'classify'  => '生产派工',
			'state'     => '已确认',
		);
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//单据编号
		);

		//初始化
		$and  = " and id not in (select distinct sendId from process_report where coid = '" . self::$coid . "')";
		$mAnd = '';

		if ($this->post('machiningOrderNo')) {
			$and .= " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
		}
		if ($this->post('code')) {
			$mAnd .= " and code like '%" . $this->post('code') . "%'";
		}
		if ($this->post('materialName')) {
			$mAnd .= " and name like '%" . $this->post('materialName') . "%'";
		}
		if ($mAnd) {
			$and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
		}
		if ($this->post('startTime')) {
			$and .= self::timeComparison($this->post('startTime'), field: 'startDate');
		}
		if ($this->post('endTime')) {
			$and .= self::timeComparison($this->post('endTime'), field: 'endDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("waitReport", "listId")
        );
		$url      = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate       = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"report" => $isProductCard?[]:array("title" => "报工", "click" => "layer('processReport','edit',{sourceId:'" . $array['id'] . "'})"),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
				'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产派工单&id=" . $array['id'] . "')"),
			);
            $material       = query('material', "id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'tags':
                        $tags           = orderTagClass::getTagName($array['id']);
                        $row[] = $tags;
                        break;
                    case 'line':
                        $line           = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['workshop'] . '-' . $line['name'];
                        break;
                    case 'process':
                        $process        = query('process', "id = '$array[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'team':
                        $team           = query('team', "id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'equipment':
                        $row[] = equipmentClass::getName($array['deviceId']);
                        break;
                    case 'orderType':
                        $row[] = $this->orderTypeOption[$array['orderType']];
                        break;
                    case 'sourceNo':
                        $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
                        $row[] = $machiningOrder['orderNo'];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='waitReport'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	public function batchSend()
	{
		//生成表单
		$html = $this->layerEdit(array(
			"table"      => array(
				array(
					"班组：" => selectMultiple(array("name" => "teamId", "title" => "班组", 'where' => "coid = '" . self::$coid . "'", "table" => "team", 'sqlField' => 'name', 'sqlId' => 'id')),
				),
                array(
                    "设备：" => selectMultiple(array("name" => "deviceId", "title" => "设备", 'where' => "coid = '" . self::$coid . "'", "table" => "equipment", 'sqlField' => 'name', 'sqlId' => 'id')),
                ),
			),
		));
		//返回
		return $this->layer(array("title" => "批量派工", 'winFix' => true, "height" => 200, "html" => $html, 'formTwo' => 'listForm'));
	}

	public function batchSendEdit()
	{
		$listId = $this->post('listId');
		$teamId = $this->post('teamId');
		$deviceId = $this->post('deviceId');
		if (static::is_null_array($listId)) {
			$json['warn'] = '请选择数据';
		} elseif (empty($teamId) && empty($deviceId)) {
			$json['warn'] = '请至少选择一项';
		} else {
			$x    = 0;
			$text = '';
			$team = query('team', "id = '$teamId'");
			foreach ($listId as $id) {
				$machiningSendOrder = query(self::table, "id = '$id'");
				$warn               = update(array('table' => self::table, 'field' => ['teamId' => $teamId,'deviceId'=>$deviceId], 'where' => "id = '$id'"));
				if ($warn == '更新成功') {
					$x++;
					$text .= "生产派工单【{$machiningSendOrder['orderNo']}】<br>";
				} else {
					$text .= "生产派工单【{$machiningSendOrder['orderNo']}】派工失败<br>";
				}
			}
			if ($text) {
				$text = $this->control['name'] . '批量派工了生产派工单如下：' . $text;
				$this->logText(["type" => self::page, "text" => $text]);
			}
			$json['warn']     = 2;
			$_SESSION['warn'] = "批量派工了{$x}个派工单";
		}
		return json_encode($json, 320);
	}

	/**
	 * 批量选择班次
	 */
	public function batchChooseTime()
	{
		$page = self::page;
		return <<<eof
<span onclick="layer('$page','chooseTime',{})" class="del-row-button">批量</span>
<script>
function batchChooseTime(){
    let val = $("[name='chooseDate']").val();
    let teamTypeChoose = $("[name='teamTypeChoose']").val();
    $("[name='teamNo[]']").val(val);
     $("[name='teamType[]']").val(teamTypeChoose);
    $('#machiningSendOrderChooseTime').hide();
}
</script>
eof;
	}

	public function chooseTime()
	{
        $teamType =  para('teamType','，');
		//生成表单
		$html = $this->layerEdit(array(
			"table"  => array(
				array(
					'班次' => text(['name' => 'chooseDate', 'laydate' => [], 'value' => $this->date]). select(array('name' => 'teamTypeChoose', 'option' =>$teamType, 'title' => '请选择', 'value' => $teamType[0])),
				),
			),
		));
		//返回
		return $this->layer(array(
		    "title" => "批量选择班次",
            'zindex'=>10,
            "height" => 200,
            "width" => 700,
            "html" => $html,
            'button' => "<input onclick=\"batchChooseTime()\" type='button' class='button' value='确定'>"
        ));
	}

	public function batchReport()
	{
        $button = "";
        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
	    if ($isProductCard){
	        $html = "当前是【生产流转卡】流程，不能使用派工单报工";
        }else{
            $listArr          = $this->post('listId');
            $tr[]             = ['', '派工单号', '工序', '物料名称', '单位', '派工数量', '实际产量', '班组/人员', '班次' . $this->batchChooseTime()];
            $teamDetail       = query('team_detail as a join team as b on a.orderId = b.id', "a.stid = '" . self::$stid . "' and b.coid = '" . self::$coid . "' and b.state = '启用'", "b.id as id,b.name as name");
            $teamDetail['id'] = $teamDetail['id'] ?? '';

            $teamDetail['name'] = $teamDetail['name'] ?? '';
            $teamType =  para('teamType','，');
            if (is_array($listArr)) {
                foreach ($listArr as $k=>$id) {
                    $machiningSendOrder = query('machining_send_order', "id = '$id'");
                    $team               = query('team', "id = '$machiningSendOrder[teamId]'");
                    $teamId             = $machiningSendOrder['teamId'] ?: $teamDetail['id'];
                    $teamName           = $team['name'] ?: $teamDetail['name'];
                    $process            = query('process', "id = '$machiningSendOrder[processId]'");
                    $routingDetail      = query('routing_detail', "id = '$machiningSendOrder[routingMxId]'");
                    $hide               = 'hide';
                    if ($routingDetail['valuationType'] == '个人计件') {
                        $hide = '';
                    }
                    $teamStaff = query('team_detail', "stid = '" . self::$stid . "' and orderId = '$teamId'");
                    $tr[]      = [
                        componentClass::tablePperation($k+1,"delTableRow(this)").
                        hidden(array('name' => 'sendId[]', 'value' => $id)),
                        $machiningSendOrder['orderNo'],
                        $process['name'],
                        materialClass::getName($machiningSendOrder['materialId']),
                        $machiningSendOrder['unit'],
                        self::lostZero($machiningSendOrder['num'], 'numPrecision'),
                        text(array('name' => 'factNum[]', 'class' => 'width100', 'other' => self::digitalFiltering('numPrecision'), 'value' => self::lostZero($machiningSendOrder['num'], 'numPrecision'))),
                        text(array("name" => "teamName[]", 'class' => 'width100 teamId', 'value' => $teamName, "title" => "班组")) . hidden(array('name' => 'teamId[]', 'value' => $teamId)) . "<span class='$hide teamStaff'>" . text(array("name" => "teamStaffName[]", 'class' => 'width100 teamStaffId', 'value' => $teamStaff['id'] ? $this->control['name'] : '', "title" => "员工")) . hidden(array('name' => 'teamStaffId[]', 'value' => $teamStaff['id'] ? self::$stid : '')) . "</span>",
                        text(array('name' => 'teamNo[]', 'class' => 'width100', 'laydate' => [], 'value' => $this->date)). select(array('name' => 'teamType[]', 'option' => $teamType, 'title' => '请选择', 'value' =>$teamType[0])),
                    ];
                }
            }
            $htm =  $this->tableMany(array('tr' => $tr)) . <<<of
<script>
$(".teamId").each(function() {
    $(this).bigAutocomplete({
        url:root + 'control/adIndex.html?cla=machiningSendOrder&fun=getTeam',
        callback:function(data,e){
             e.siblings("input[name='teamId[]']").val(data.id)
             $.post(root+'control/adIndex.html?cla=machiningSendOrder&fun=getTeamStaffInput',{teamId:data.id},function(res) {
                 e.parent().find(".teamStaff").empty().append(res.html);
             },'json')
    }})
})
$(".teamStaffId").each(function() {
    let obj = $(this);
    obj.bigAutocomplete({
        param:{
            teamId: obj.parent().parent().find("input[name='teamId[]']").val()
        },
        url:root + 'control/adIndex.html?cla=machiningSendOrder&fun=getTeamStaff',
        callback:function(data,e){
          e.siblings("input[name='teamStaffId[]']").val(data.id)
    }})
})
</script>
<style>

</style>
of;
            $button = "<input onclick=\"subForm('machiningSendOrderBatchReportForm',root+'control/adIndex.html?cla=machiningSendOrder&fun=batchReportEdit')\" type='button' class='button' value='提交'>";
            $html   = "<div style='padding: 10px' class='layerList'><form name='machiningSendOrderBatchReportForm'>".$htm. "</form></div>";

        }

		//返回
		return $this->layer(array("title" => "批量报工", "height" => 600, "width" => 1200, "html" => $html, "button" => $button));
	}


	public function batchReportEdit()
	{
		$idArr          = $this->post('sendId');
		$teamNoArr      = $this->post('teamNo');
		$teamTypeArr = $this->post('teamType');
		$teamIdArr      = $this->post('teamId');
		$factNumArr     = $this->post('factNum');
		$teamStaffIdArr = $this->post('teamStaffId');
		if (!$this->power('machiningSendOrderWaitReport', "edit")) {
			$json['warn'] = "权限不足";
		} elseif (static::is_null_array($idArr)) {
			$json['warn'] = '未找到报工的数据';
		} elseif (static::is_null_array($teamNoArr)) {
			$json['warn'] = '请选择班次';
		} elseif (static::is_null_array($teamIdArr)) {
			$json['warn'] = '请选择班组';
		} elseif (static::is_null_array($factNumArr)) {
			$json['warn'] = '请填写实际产量';
		} else {
			$x              = 0;
//			$teamTypeOption = explode('，', para('teamType'));
			foreach ($idArr as $k => $id) {
				$mainId             = suiji();
				$machiningSendOrder = query('machining_send_order', "id = '$id'");
				$routing_detail     = query('routing_detail', "id = '$machiningSendOrder[routingMxId]'");
				$factNumArr[$k]     = self::formattingFigure($factNumArr[$k], 'numPrecision');
				//赋值
				$field            = array(
					"id"               => $mainId,
					'coid'             => self::$coid,
					'state'            => '草稿',
					"sendId"           => $machiningSendOrder['id'],
					'machiningOrderId' => $machiningSendOrder['machiningOrderId'],
					'teamNo'           => $teamNoArr[$k],
					"teamId"           => $teamIdArr[$k],
					'teamType'         => $teamTypeArr[$k],
					"yield"            => $factNumArr[$k],
					'unit'             => $machiningSendOrder['unit'],
					'materialId'       => $machiningSendOrder['materialId'],
					'processId'        => $machiningSendOrder['processId'],
					'routingId'        => $machiningSendOrder['routingId'],
					'routingMxId'      => $machiningSendOrder['routingMxId'],
					'lineId'           => $machiningSendOrder['lineId'],
					'valuationType'    => $routing_detail['valuationType'],
					'stid'             => $this->control['stid'],
				);
				$userNo           = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'BG' . date('Ymd'),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => " and coid = '" . self::$coid . "'",
				], $field);
				$field['orderNo'] = $userNo;
				$warn             = insert(array("table" => 'process_report', "field" => $field));
				if ($warn == '新增成功') {
					$x++;
					//添加日志
					$text = $this->control['name'] . "批量报工了生产派工单：【{$machiningSendOrder['orderNo']}】,ID：" . $id;
					$this->logText(array("type" => self::page, "text" => $text));
					auditClass::operateRecord($mainId, '工序报工', '新建');
					if ($field['valuationType'] == '个人计件') {
						delete(array('table' => 'process_report_staff', 'where' => "orderId = '$mainId' and coid = '" . self::$coid . "'"));
						static::insert(array(
							'table' => 'process_report_staff',
							'field' => array(
								'id'      => suiji(),
								'coid'    => self::$coid,
								'orderId' => $mainId,
								'stid'    => $teamStaffIdArr[$k],
							),
						));
					}
				}
			}
			$_SESSION['warn'] = "成功报工了{$x}个派工单";
			$json['warn']     = 2;
		}
		return json_encode($json, 320);
	}

	public function getTeam()
	{
		$val          = $this->post('keyword');//关键词
		$json['data'] = [];
		$where        = " and coid='" . self::$coid . "'";
		if ($val) {
			$where .= " and (name like '%$val%')";
		}
		$all = find(array('table' => 'team', 'where' => "coid='" . self::$coid . "' and state ='启用' $where order by orderNo asc"));
		foreach ($all['array'] as $array) {
			$json['data'][] = array('title' => $array['name'], 'id' => $array['id']);
		}
		$json['warn'] = 2;
		return json_encode($json, 320);
	}

	public function getTeamStaff()
	{
		$teamId       = $this->post('teamId');
		$val          = $this->post('keyword');//关键词
		$json['data'] = [];
		$where        = '';
		if ($val) {
			$where .= " and (name like '%$val%')";
		}
		$all = find(array(
		    'table' => 'staff',
            'where' => "stid in (select stid from team_detail where orderId='" . $teamId . "' and coid = '" . self::$coid . "' ) $where order by time asc"
        ));
		foreach ($all['array'] as $array) {
			$json['data'][] = array('title' => $array['name'], 'id' => $array['stid']);
		}
		$json['warn'] = 2;
		return json_encode($json, 320);
	}

	public function getTeamStaffInput()
	{
		$teamId       = $this->post('teamId');
		$suiji        = suiji();
		$json['html'] = text(array(
		    "name" => "teamStaffName[]",
            'id' => $suiji,
            'class' => 'width100 teamStaffId',
            "title" => "员工"
            )) . hidden(array('name' => 'teamStaffId[]')) .
		                <<<eof
<script>
$("#{$suiji}").bigAutocomplete({
        param:{
            teamId: '{$teamId}'
        },
        url:root + 'control/adIndex.html?cla=machiningSendOrder&fun=getTeamStaff',
        callback:function(data,e){
          e.siblings("input[name='teamStaffId[]']").val(data.id)
    }})
</script>
eof;
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function partReportOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm();
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	public function partReport()
	{
        $html = $this->partReportOptions(false);
        //控件
        $button = "";
        if ($this->power('machiningSendOrderPartReport', "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','reportComplete',{})\" class='spanButton'>报工完成</span>\n";
        }
        if ($this->power('machiningSendOrderPartReport', "print")) {
            $button .= "<span onclick=\"get_list_box('partReportForm')\" class='spanButton'>批量打印</span>\n";
        }
        if ($this->power('machiningSendOrderPartReport', "edit")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchAddTags',{formName:'partReportForm'})\" class='spanButton'>批量打标签</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	public function partReportSearch()
	{
		//全等查询数组
		$equal = array(
			'coid'      => self::$coid,
			"type"      => $this->post('type'),
			"processId" => $this->post('processId'),
			"lineId"    => $this->post('lineId'),
			'classify'  => '生产派工',
			'state'     => '已确认',
		);
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//单据编号
		);

		//初始化
		$and  = " and workFlow = 0 and id in (select distinct sendId from process_report where coid = '" . self::$coid . "')";
		$mAnd = '';

		if ($this->post('machiningOrderNo')) {
			$and .= " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
		}
		if ($this->post('code')) {
			$mAnd .= " and code like '%" . $this->post('code') . "%'";
		}
		if ($this->post('materialName')) {
			$mAnd .= " and name like '%" . $this->post('materialName') . "%'";
		}
		if ($mAnd) {
			$and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
		}
		if ($this->post('startTime')) {
			$and .= self::timeComparison($this->post('startTime'), field: 'startDate');
		}
		if ($this->post('endTime')) {
			$and .= self::timeComparison($this->post('endTime'), field: 'endDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("partReportForm", "listId")
        );
		$url      = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
		//获取记录
        $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate       = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"report" => $isProductCard?[]:array("title" => "报工", "click" => "layer('processReport','edit',{sourceId:'" . $array['id'] . "'})"),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
				'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产派工单&id=" . $array['id'] . "')"),
			);
			$closeSign      = $array['isClose'] ? "<span class='no-choose'></span>" : '';//关闭单据颜色显示标志
            $material       = query('material', "id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate) . $closeSign;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'tags':
                        $tags           = orderTagClass::getTagName($array['id']);
                        $row[] = $tags;
                        break;
                    case 'line':
                        $line           = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['workshop'] . '-' . $line['name'];
                        break;
                    case 'process':
                        $process        = query('process', "id = '$array[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'team':
                        $team           = query('team', "id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'reportNum':
                        //报工数量
                        $reportNum = find(array('table' => 'process_report', 'where' => "sendId ='$array[id]' and processId = '$array[processId]' and state = '已确认'", 'sum' => "yield"));
                        $row[] = self::lostZero($reportNum, 'numPrecision');
                        break;
                    case 'equipment':
                        $row[] = equipmentClass::getName($array['deviceId']);
                        break;
                    case 'orderType':
                        $row[] = $this->orderTypeOption[$array['orderType']];
                        break;
                    case 'sourceNo':
                        $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
                        $row[] = $machiningOrder['orderNo'];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='partReportForm'>" . $li . "</form>" . machiningOrderClass::closeJs() . $page['button'] . clear;
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function reportedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已报工');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	public function reported()
	{
        $html = $this->reportedOptions(false);
        //控件
        $button = "";
        if ($this->power('machiningSendOrderReported', "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','cancelReport',{})\" class='spanButton'>取消完成</span>\n";
        }
        if ($this->power('machiningSendOrderReported', "print")) {
            $button .= "<span onclick=\"get_list_box('reportedForm')\" class='spanButton'>批量打印</span>\n";
        }
        if ($this->power('machiningSendOrderReported', "edit")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchAddTags',{formName:'reportedForm'})\" class='spanButton'>批量打标签</span>\n";
        }
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	public function reportedSearch()
	{
		//全等查询数组
		$equal = array(
			'coid'      => self::$coid,
			"type"      => $this->post('type'),
			"processId" => $this->post('processId'),
			"lineId"    => $this->post('lineId'),
			'classify'  => '生产派工',
			'state'     => '已确认',
			'workFlow'  => 1,
		);
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//单据编号
		);

		//初始化
		$and  = "";
		$mAnd = '';

		if ($this->post('machiningOrderNo')) {
			$and = " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
		}
		if ($this->post('code')) {
			$mAnd .= " and code like '%" . $this->post('code') . "%'";
		}
		if ($this->post('materialName')) {
			$mAnd .= " and name like '%" . $this->post('materialName') . "%'";
		}
		if ($mAnd) {
			$and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
		}
		if ($this->post('startTime')) {
			$and .= self::timeComparison($this->post('startTime'), field: 'startDate');
		}
		if ($this->post('endTime')) {
			$and .= self::timeComparison($this->post('endTime'), field: 'endDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("reportedForm", "listId")
        );
		$url      = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
				'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
				'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产派工单&id=" . $array['id'] . "')"),
			);
            $closeSign      = $array['isClose'] ? "<span class='no-choose'></span>" : '';//关闭单据颜色显示标志
            $material       = query('material', "id = '$array[materialId]'");
            $liButton[] = $this->dominate($dominate) . $closeSign;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'tags':
                        $tags           = orderTagClass::getTagName($array['id']);
                        $row[] = $tags;
                        break;
                    case 'line':
                        $line           = query('product_line', "id = '$array[lineId]'");
                        $row[] = $line['workshop'] . '-' . $line['name'];
                        break;
                    case 'process':
                        $process        = query('process', "id = '$array[processId]'");
                        $row[] = $process['name'];
                        break;
                    case 'team':
                        $team           = query('team', "id = '$array[teamId]'");
                        $row[] = $team['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'reportNum':
                        //报工数量
                        $reportNum = find(array('table' => 'process_report', 'where' => "sendId ='$array[id]' and processId = '$array[processId]' and state = '已确认'", 'sum' => "yield"));
                        $row[] = self::lostZero($reportNum, 'numPrecision');
                        break;
                    case 'equipment':
                        $row[] = equipmentClass::getName($array['deviceId']);
                        break;
                    case 'orderType':
                        $row[] = $this->orderTypeOption[$array['orderType']];
                        break;
                    case 'sourceNo':
                        $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
                        $row[] = $machiningOrder['orderNo'];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='reportedForm'>" . $li . "</form>" . machiningOrderClass::closeJs() . $page['button'] . clear;
		return json_encode($json, 320);
	}

	public function reportComplete()
	{
		//生成表单
		$html = $this->layerEdit(array(
			"table"      => array(
				array(
					must . "提示：" => '是否确认将所选数据标记为报工已完成？',
				),
			),
		));
		//返回
		return $this->layer(array("title" => "报工完成", "height" => 165, "width" => 600, "html" => $html, 'formTwo' => 'partReportForm'));
	}

	public function reportCompleteEdit()
	{
		$listId = $this->post('listId');
		if (static::is_null_array($listId)) {
			$json['warn'] = '请选择数据';
		} else {
			$x    = 0;
			$text = '';
			foreach ($listId as $id) {
				$info     = query(self::table, "id = '$id'");
				$material = query('material', "id = '$info[materialId]'");
				$all      = find(array('table' => 'process_report', 'where' => "sendId = '$id' and coid = '" . self::$coid . "'"));
				$num      = 0;
				foreach ($all['array'] as $array) {
					$num += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $info['unit'], $array['yield']);
				}
				if ($num >= $info['num'] * (1 - $material['machiningTolerance'])) {
					$warn = update(array('table' => self::table, 'field' => ['workFlow' => 1], 'where' => "id = '$id'"));
					if ($warn == '更新成功') {
						$x++;
						$text .= "生产派工单【{$info['orderNo']}】更新为报工已完成<br>";
					} else {
						$text .= "生产派工单【{$info['orderNo']}】更新为报工已完成失败<br>";
					}
				} else {
					$text .= "生产派工单【{$info['orderNo']}】更新为报工已完成失败：还未达到最低完成数量<br>";
				}
			}
			if ($text) {
				$text = $this->control['name'] . '批量标记派工单报工已完成如下：' . $text;
			}
			$this->logText(["type" => 'machiningSendOrderPartReport', "text" => $text]);
			$json['warn']     = 2;
			$_SESSION['warn'] = "成功操作了{$x}条数据";
		}
		return json_encode($json, 320);
	}

	public function cancelReport()
	{
		//生成表单
		$html = $this->layerEdit(array(
			"table"      => array(
				array(
					must . "提示：" => '是否确认取消将所选数据的报工已完成？',
				),
			),
		));
		//返回
		return $this->layer(array("title" => "取消报工完成", "height" => 165, "width" => 600, "html" => $html, 'formTwo' => 'reportedForm'));
	}

	public function cancelReportEdit()
	{
		$listId = $this->post('listId');
		if (static::is_null_array($listId)) {
			$json['warn'] = '请选择数据';
		} else {
			$x    = 0;
			$text = '';
			foreach ($listId as $id) {
				$info = query(self::table, "id = '$id'");
				$warn = update(array('table' => self::table, 'field' => ['workFlow' => 0], 'where' => "id = '$id'"));
				if ($warn == '更新成功') {
					$x++;
					$text .= "生产派工单【{$info['orderNo']}】取消报工已完成<br>";
				} else {
					$text .= "生产派工单【{$info['orderNo']}】取消报工已完成失败<br>";
					break;
				}
			}
			if ($text) {
				$text = $this->control['name'] . '批量取消派工单报工已完成如下：' . $text;
			}
			$this->logText(["type" => 'machiningSendOrderReported', "text" => $text]);
			$json['warn']     = 2;
			$_SESSION['warn'] = "成功操作了{$x}条数据";
		}
		return json_encode($json, 320);
	}

	/**
	 * 工序委外
	 */
	public function outsource()
	{
		//生成表单
		$html = $this->layerEdit(array(
			"table"      => array(
				array(
					must . "委外单位：" => selectMultiple(array(
					    "name" => "companyId",
                        "title" => "请选择",
                        "table" => "supplier",
                        'where' => " state ='启用' and coid = '" . self::$coid . "' and outsource = '是' order by time",
                        'sqlField' => 'name',
                        'sqlId' => 'id'
                    )),
				),
			),
		));
		//返回
		return $this->layer(array("title" => "工序委外", 'winFix' => true, "height" => 165, "width" => 600, "html" => $html, 'formTwo' => 'waitReport'));
	}

	public function outsourceEdit()
	{
		$listId    = $this->post('listId');
		$companyId = $this->post('companyId');
		if (static::is_null_array($listId)) {
			$json['warn'] = '请选择数据';
		} elseif (empty($companyId)) {
			$json['warn'] = '请选择委外单位';
		} else {
			$x    = 0;
			$text = '';
			foreach ($listId as $id) {
				$info = query(self::table, "id = '$id'");
				$warn = update(array('table' => self::table, 'field' => ['classify' => '委外派工', 'companyId' => $companyId], 'where' => "id = '$id'"));
				if ($warn == '更新成功') {
					$x++;
					$text .= "生产派工单【{$info['orderNo']}】转为了委外派工单<br>";
				} else {
					$text .= "生产派工单【{$info['orderNo']}】转为委外派工单失败<br>";
					break;
				}
			}
			if ($text) {
				$text = $this->control['name'] . '批量转委外派工单如下：' . $text;
			}
			$this->logText(["type" => self::page, "text" => $text]);
			$json['warn']     = 2;
			$_SESSION['warn'] = "成功操作了{$x}条数据";
		}
		return json_encode($json, 320);
	}


	public function batchConfirm(): bool|string
	{
		//生成表单
		$html = $this->layerEdit(array(
			"table"      => array(
				array(
					"提示：" => "是否批量确认所选的生产派工单？",
				),
			),
		));
		//返回
		return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
	}

	public function batchConfirmEdit(): bool|string
	{
		$listId = $this->post('listId');
		if (static::is_null_array($listId)) {
			$json['warn'] = '请选择数据';
		} else {
			$x    = 0;
			$text = '';
			$this->startTrans();
			$json['warn'] = '';
			foreach ($listId as $id) {
				$machiningSendOrder = query(self::table, "id = '$id'");
				if (empty($machiningSendOrder['num']) || $machiningSendOrder['num'] <= 0) {
					$json['warn'] = "派工单【{$machiningSendOrder['orderNo']}】的派工数量为0";
					break;
				} elseif (empty($machiningSendOrder['processId'])) {
					$json['warn'] = "派工单【{$machiningSendOrder['orderNo']}】未选择工序";
					break;
				}
				$warn = update(array(
				    'table' => self::table,
                    'field' => ['state' => '已确认', 'checkId' => self::$stid, 'confirmTime' => $this->time],
                    'where' => "id = '$id'"
                ));
				if ($warn == '更新成功') {
					$x++;
					$text .= "生产派工单【{$machiningSendOrder['orderNo']}】,确认成功<br>";
					auditClass::operateRecord($id, '生产派工单', '确认');
				} else {
					$json['warn'] = "派工单【{$machiningSendOrder['orderNo']}】确认失败";
					break;
				}
			}
			if (empty($json['warn'])) {
				$this->commitTrans();
				$text = $this->control['name'] . '批量确认了生产派工单如下：' . $text;
				$this->logText(["type" => self::page, "text" => $text]);
				$json['warn']     = 2;
				$_SESSION['warn'] = "成功确认了{$x}条数据";
			} else {
				$this->rollback();
			}
		}
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return string
	 */
    public function edit()
    {
        $id               = $this->post('id') ?: suiji();
        $info             = query(self::table, " id = '" . $id . "' ");
        $machining_order  = query('machining_order', "id = '$info[machiningOrderId]'");
        $machining_ordeMx = query('machining_order_mx', "id = '$info[machiningOrderMxId]'");
        $material         = query('material', "id = '$machining_ordeMx[materialId]'");
        $materialName     = $machining_order['id'] ? ($material['code'] . '-' . $material['name'] . '-' . $material['model']) : '';
        $line             = query('product_line', "id = '$info[lineId]'");
        $lineName         = $line['workshop'] . '-' . $line['name'];
        //表单
        $html = $this->layerEdit([
            "table" => [
                array(
                    must . "源单类型：" => radio(array('name' => 'orderType', 'value' => $this->orderTypeOption, 'checked' => $info['orderType'] ?: '生产计划')),
                    must . "关联源单：" => "<span id='machiningOrderNo'>" .
                        $machining_order['orderNo'] .
                        "</span>
                        <span style='margin-left: 5px' onclick=\"layer('{$this->get('cla')}','addOrder',$('form[name=machiningSendOrderEditForm]').serialize())\" class='del-row-button' >选择</span>",
                ),
                array(
                    "派工单类型：" => "<span id='sendType'>{$info['type']}</span>",
                    must."单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ),
                array(
                    "物料：" => "<span id='material'>{$materialName}</span>" . hidden(array('name' => 'machiningOrderMxId', 'value' => $machining_ordeMx['id'])),
                    "生产线：" => "<span id='productLine'>{$lineName}</span>",
                ),
                array(
                    '单位：' => "<span id='unit'>{$info['unit']}</span>",
                    "班组：" => selectMultiple(array("name" => "teamId", 'value' => $info['teamId'], "title" => "班组", "table" => "team", 'where' => " state ='启用' and coid = '" . self::$coid . "'", 'sqlField' => 'name', 'sqlId' => 'id')),
                ),
                array(
                    must . "派工数量：" => text(array("name" => "num", 'other' => self::digitalFiltering('numPrecision'), "value" => self::lostZero($info['num'], 'numPrecision'))),
                    must . "工序：" => "<div id='process' style='width: 100%;'>" . selectMultiple(array("name" => "processId", 'value' => $info['processId'], "title" => "工序", "table" => "process", 'where' => " state ='启用' and coid = '" . self::$coid . "' and id in (select processId from routing_detail where orderId = '$machining_ordeMx[routingId]')", 'sqlField' => 'name', 'sqlId' => 'id')) . "</div>",
                ),
                array(
                    "计划开工时间：" => text(array("name" => "startDate", 'laydate' => [], "value" => self::null($info['startDate'], false))),
                    "计划完工时间：" => text(array("name" => "endDate", 'laydate' => [], "value" => self::null($info['endDate'], false))),
                ),
                array(
                    "备注：" => textarea(array("name" => "text", "value" => $info['text'])),
                ),
            ],
        ]);
        $html .= $this->js();
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 450, "html" => $html));
    }

	public function js(): string
	{
		return <<<efo
<script>
          //选择生产产品
    function addMaterial(){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='mxForm']").serialize(),function(res) {
                 if (res.warn ==2){
                   $('#machiningSendOrderAddOrder').hide()
                   $("#unit").html(res.data.unit);
                   $("#productLine").html(res.data.line);
                   $("#machiningOrderNo").html(res.data.orderNo);
                   $("#sendType").html(res.data.type);
                   $("#material").html(res.data.materialName);
                   $("#process").empty().append(res.data.process);
                   $("[name='machiningOrderMxId']").val(res.data.id);
                   $("[name='num']").val(res.data.num);
                   $("[name='startDate']").val(res.data.startDate);
                   $("[name='endDate']").val(res.data.endDate);
                 }else{
                     msg(res.warn);
                 }
            },'json');
    }
</script>
efo;
	}

	/**
	 * 从生产计划中选择
	 *
	 * @return bool|string
	 */
	public function addOrder(): bool|string
	{
		$html   =
			text(array("name" => "orderNo", "title" => "生产计划单号")) .
			text(array("name" => "code", "title" => "产品编码")) .
			text(array("name" => "materialName", "title" => "产品名称")) .
			text(array("name" => "model", "title" => "规格型号")) .
			hidden(array('name' => 'orderType', 'value' => $this->post('orderType'))) .
			hidden(array('name' => 'id', 'value' => $this->post('id')));
		$button = "<input style='margin-left: 5px' onclick=\"addMaterial()\" type='button' class='searchSub' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
	}

	/**
	 * 从生产计划中选择
	 *
	 * @return bool|string
	 */
	public function addOrderSearch(): bool|string
	{
		$where = " a.coid='" . self::$coid . "'";
		$and   = " and b.isClose = 0";
		$like  = [
			'b.orderNo' => $this->post('orderNo'),
			'c.name'    => $this->post('materialName'),
			'c.code'    => $this->post('code'),
			'c.model'   => $this->post('model'),
		];
		$equal = [
			'b.state'     => '已确认',
			'b.orderType' => $this->post('orderType'),
		];

		$where .= search(["like" => $like, "=" => $equal]) . $and;
		$page  = $this->page([
			"table"   => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
			'field'   => "a.*,c.name,c.code,c.model,c.unit,b.orderNo,b.lineId",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => "b.recordDate desc,a.`list` asc",
		]);
		//获取表头
		$tr[] = ['', '源单单号', '生产线', '产品编码', '产品名称', '规格型号', '单位', '计划数量'];// '关联销售单号/关联生产计划单',
		//获取记录
		foreach ($page['array'] as $array) {
			$line        = query('product_line', "id = '$array[lineId]'");
			$tr[]        = array(
				"<input name='mxId' type='radio' value='{$array['id']}'>",
				$array['orderNo'],
				$line['workshop'] . '-' . $line['name'],
				$array['code'],
				$array['name'],
				$array['model'],
				$array['unit'],
				self::lostZero($array['num'], 'numPrecision'),
			);
		}
		$json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 从生产计划中选择
	 */
	public function addOrderEdit(): bool|string
	{
		$mxId = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxId)) {
			$json['warn'] = '请选择生产计划单产品';
		} else {
			$json['warn']     = 2;
			$machiningOrderMx = query('machining_order_mx', "id = '$mxId'");
			$machiningOrder   = query('machining_order', "id = '$machiningOrderMx[orderId]'");
			$line             = query('product_line', "id = '$machiningOrder[lineId]'");
			$material         = query('material', " id = '$machiningOrderMx[materialId]'");
			//已派工数量
			$num          = find(array(
			    'table' => self::table,
                'where' => "machiningOrderMxId = '$machiningOrderMx[id]' and id !='" . $this->post('id') . "'",
                'sum' => "num"
            ));
			$json['data'] = [
				'id'           => $machiningOrderMx['id'],
				'line'         => $line['workshop'] . '-' . $line['name'],
				'unit'         => $machiningOrderMx['unit'],
				'type'         => $machiningOrder['type'],
				'orderNo'      => $machiningOrder['orderNo'],
				'startDate'    => $machiningOrder['startDate'],
				'endDate'      => $machiningOrder['endDate'],
				'num'          => ($machiningOrderMx['num'] - $num) <= 0 ? 0 : self::formattingFigure($machiningOrderMx['num'] - $num, 'numPrecision'),
				'materialName' => $material['code'] . '-' . $material['name'] . '-' . $material['model'],
				'process'      => selectMultiple(array(
				    "name" => "processId",
                    "title" => "工序",
                    "table" => "process",
                    'where' => " state ='启用' and coid = '" . self::$coid . "' and id in (select processId from routing_detail where orderId = '$machiningOrderMx[routingId]')",
                    'sqlField' => 'name',
                    'sqlId' => 'id'
                )),
			];
		}
		return json_encode($json, 320);
	}


	/*编辑*/
	public function editEdit()
	{
		$id = $this->post('id') ?: self::getId();
		//赋值
		$field      = array(
            "recordDate"          => $this->post('recordDate'),
			"startDate"          => $this->post('startDate'),
			"endDate"            => $this->post('endDate'),
			"machiningOrderMxId" => $this->post('machiningOrderMxId'),//备注
			"processId"          => $this->post('processId'),
			"num"                => $this->post('num') ? self::formattingFigure($this->post('num'), 'numPrecision') : '',
			'teamId'             => $this->post('teamId'),
			"text"               => $this->post('text'),
		);
		$annotation = [
			"machiningOrderMxId" => '生产计划',
			"processId"          => '工序',
			"num"                => '派工数量',
		];
		$rules      = [
			"machiningOrderMxId" => 'required',
			"processId"          => 'required',
			"num"                => 'required|numeric',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$info = query(self::table, " id = '" . $id . "' ");
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "权限不足";
		} elseif ($info['state'] == '已确认') {
			$json['warn'] = '此生产派工单已确认，不能编辑';
		} elseif (!empty($field['startDate']) && !empty($field['endDate']) && strtotime($field['endDate']) < strtotime($field['startDate'])) {
			$json['warn'] = '计划完工时间不能小于计划开工时间';
		} else {
			$json['warn']     = '';
			$machiningOrderMx = query('machining_order_mx', "id = '$field[machiningOrderMxId]'");
			$machiningOrder   = query('machining_order', "id = '$machiningOrderMx[orderId]'");
			$occupyNum        = $this->judgeExceedNum($machiningOrderMx['id'], $id, $field['processId'], $machiningOrderMx['unit']);
			if (!optionSettingClass::getSettingItem('生产', 'allowMoreProcessNum') && $machiningOrderMx['num'] < round($occupyNum + $field['num'], 2)) {
				$json['warn'] = "派工数量已超过此加工单数量";
			}
			if (empty($json['warn'])) {
				$field['type']             = $machiningOrder['type'];
				$field['unit']             = $machiningOrderMx['unit'];
				$field['lineId']           = $machiningOrder['lineId'];
				$field['orderType']        = $machiningOrder['orderType'];
				$field['machiningOrderId'] = $machiningOrder['id'];
				$field['materialId']       = $machiningOrderMx['materialId'];
				$field['routingId']        = $machiningOrderMx['routingId'];
				$routingDetail             = query('routing_detail', "orderId = '$field[routingId]' and processId ='$field[processId]' order by list");
				$field['classify']         = $routingDetail['isOut'] == '是' ? '委外派工' : '生产派工';
				$field['routingMxId']      = $routingDetail['id'];
				if (empty($info['id'])) {
					$userNo       = codeTemplateClass::generateCode(self::page, [
						'prefix' => 'SCPG' . date('Ymd'),
						'table'  => self::table,
						'field'  => 'orderNo',
						'where'  => " and coid = '" . self::$coid . "'",
					], $field);
					$field        = array_merge($field, array("id" => $id,  'coid' => self::$coid, 'orderNo' => $userNo, 'state' => '草稿', 'stid' => $this->control['stid']));
					$json['warn'] = insert(array("table" => self::table, "field" => $field));
				} else {
					$json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
				}
				if (in_array($json['warn'], array("新增成功", "更新成功"))) {
					if ($json['warn'] == '新增成功') {
						auditClass::operateRecord($id, '生产派工单', '新增');
					}
					//添加日志
					$type = mb_substr($json['warn'], 0, 2, 'utf-8');
					$text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
					$this->logText(array("type" => self::page, "text" => $text));
					//返回
					$_SESSION['warn'] = $json['warn'];
					$json['warn']     = 2;
				}
			}
		}

		$json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
		resp:
		return json_encode($json, 320);
	}


	/**
	 * 获取已派工的生产数量
	 *
	 * @param $machiningOrderMxId
	 * @param $id
	 * @param $processId
	 * @param $unit
	 * @return float|int
	 */
	public function judgeExceedNum($machiningOrderMxId, $id, $processId, $unit)
	{
		$all = find(array('table' => self::table, "where" => "coid = '" . self::$coid . "' and id !='$id' and processId = '$processId' and machiningOrderMxId = '$machiningOrderMxId'"));
		$num = 0;
		foreach ($all['array'] as $array) {
			$num += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $unit, $array['num']);
		}
		return $num;
	}

	/*出差详情*/
	public function detail(): string
	{
		//定义参数
		if (empty($this->get('id'))) {
			$html = '未找到此' . self::title;
		} else {
			$info = query(self::table, " id = '" . $this->get('id') . "' ");
			if (empty($info['id'])) {
				$html = "未找到此记录";
			} else {
				//菜单
				$data = array(
					"id" => $info['id'],
				);

				$button = [];
				if ($info['state'] == '草稿') {
					//按钮
					$button[] = [
						"name"  => "提交",
						"type"  => "弹出层",
						"cla"   => $this->get('cla'),
						"fun"   => "operate",
						"post"  => ["act" => 'commit', "id" => $info['id']],
						'style' => 'li-btn-blue-bg',
					];
				}
				if ($info['state'] != '已确认') {
					if ($this->power(self::page, "edit")) {
						//按钮
						$button[] = [
							"name"  => "编辑",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "edit",
                            "post" => ["id" => $info['id']],
						];
					}
					if ($this->power(self::page, "del")) {
						//按钮
						$button[] = [
							"name" => "删除",
							"type" => "弹出层",
							"cla"  => $this->get('cla'),
							"fun"  => "operate",
							"post" => ["act" => 'del', "id" => $info['id']],
						];
					}
				}

				if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
					$button[] = [
						"name"  => "确认",
						"type"  => "弹出层",
						"cla"   => $this->get('cla'),
						"fun"   => "operate",
						"post"  => ["act" => 'confirm', "id" => $info['id']],
						'style' => 'li-btn-blue-bg',
					];
				}
                $isProductCard = optionSettingClass::getSettingItem('生产', 'productCtrlMethod') == 'productCard';
				if ($this->power(self::page, "confirm") && $info['state'] == '已确认') {
					if (!$info['workFlow'] && !$info['isClose'] && !$isProductCard) {
						$button[] = [
							"name"  => "报工",
                            "type" => "弹出层",
                            "cla" => "processReport",
                            "fun" => "edit",
                            "post" => ["sourceId" => $info['id']],
							'style' => 'li-btn-blue-bg',
						];
					}
					if (!$info['isClose']) {
						$button[] = [
							"name" => "撤回",
							"type" => "弹出层",
							"cla"  => $this->get('cla'),
							"fun"  => "operate",
							"post" => ["act" => 'cancel', "id" => $info['id']],
						];
					}
				}
				if ($this->power(self::page, "edit") && $info['state'] == '已确认') {
					//按钮
					$isClose  = $info['isClose'] == 1 ? 0 : 1;
					$name     = $info['isClose'] == 1 ? '开启' : '关闭';
					$button[] = [
						"name" => $name,
						"type" => "点击事件",
						"fun"  => "layer('" . self::page . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$isClose}'})",
					];
				}

				$button[]       = [
					"name"  => "单据追踪",
					"type"  => "顶部页卡",
					"title" => "单据追踪",
					"url"   => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产派工单&id=" . $info['id'],
				];
				//操作记录
                $button[] = self::operateLogBut($info['id']);

				$machiningOrder = query('machining_order', "id = '$info[machiningOrderId]'");
				$line           = query('product_line', "id = '$info[lineId]'");
				$process        = query('process', "id = '$info[processId]'");
				$team           = query('team', "id = '$info[teamId]'");
				//生成表单
                $data['button'] = $this->tableShowButton($button);
				$data['html'] = $this->tableShow(array(
                    '基本信息' => array(
						array(
							"派工单类型"       => $info['orderNo'],
							"生产线"           => $line['workshop'] . '-' . $line['name'],
							"关联生产计划单号" => $machiningOrder['orderNo'],
                            "物料"     => materialClass::getName($info['materialId']),
						),
						array(
							"单位"     => $info['unit'],
							"派工数量" => self::lostZero($info['num'], 'numPrecision'),
                            "工序"         => $process['name'],
                            "计划开始时间" => $info['startDate'],
						),
						array(
							"计划下线时间" => $info['endDate'],
							'班组' => $team['name'],
                            '关联设备' =>equipmentClass::getName($info['deviceId']),
						),
						array(
							"备注" => pre($info['text']),
						),
					),
					'系统信息' => array(
						array(
							"创建人"   => self::findStaff($info['stid']),
							"创建时间" => $info['time'],
							"确认时间" => $info['confirmTime'],
                            "状态" => $info['state'],
						),
					),
				));
				//生成页面
				$html = $this->tab($data);
			}
		}
		//返回
		return $html;
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitch(): bool|string
	{
		$isClose = $this->post('type');
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
					"提示：" => "是否确认" . ($isClose == 1 ? '关闭' : '开启') . "此订单？",
				),
			), 'hidden' => hidden(array('name' => 'type', 'value' => $isClose)),
		));
		//返回
		return $this->layer(array("title" => "订单状态", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitchEdit(): bool|string
	{
		$idArr   = $this->post('id') ? [$this->post('id')] : $this->post('listId');
		$isClose = $this->post('type');
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有" . self::title . "的编辑权限";
		} elseif (empty($idArr) || !is_array($idArr)) {
			$json['warn'] = "请选择数据";
		} else {
			$field        = [
				'isClose' => $isClose,
			];
			$json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$type = $isClose == 1 ? '关闭' : '开启';
				foreach ($idArr as $id) {
					auditClass::operateRecord($id, self::title, $type);
				}
				//添加日志
				$text = $this->control['name'] . $type . "了" . self::title . "， id：【" . implode(",", $idArr) . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $type . '成功';
				$json['warn']     = 2;
			}
		}
		//返回
		return json_encode($json, 320);
	}

	/**
	 * 样式
	 *
	 * @return string
	 */
	public function style(): string
	{
		return <<<eof
<style>
.stateBlock{margin-top: 0}
.stateBlock ul li{padding: 2px 10px}
.footer-ul-parent{float: right;margin-right: 10px}
.table-top-title{height: 30px;line-height: 30px;font-size: 14px;margin-top: 20px;}
.table-top-title>ul{display: flex;flex-direction: row;padding: 2px 5px}
.table-top-title>ul>li{flex:1}
</style>
eof;
	}

	public function printEdit()
	{
		$listArr = explode(',', $this->get('listId'));
		$content = '';
		foreach ($listArr as $id) {
			$info        = query(self::table, " id = '$id'");
			$material    = query('material', "id = '$info[materialId]'");
			$company     = query('company', "coid = '" . self::$coid . "'");//公司名称
			$process     = query('process', "id = '$info[processId]'");
			$line        = query('product_line', "id = '$info[lineId]'");
			//二维码
			$url             = root . 'pay/wxpay/wxScanPng.php?url=' . urlencode("source=machining_send_order&id=" . $info['id']);
			$machiningOrder  = query('machining_order', "id = '$info[machiningOrderId]'");
			$sourceOrderType = $machiningOrder['orderType'] == '生产计划' ? '生产计划单' : '半成品加工单';
			$team            = query('team', "id = '$info[teamId]'");
			$content         .= "
<div data-op-type='new-page'></div>
                 <div>
                      <div class='printTitle' style='font-weight: bold;position: relative'>{$company['name']} <div style='position: absolute;font-weight: normal;right: 10px;top: 0;font-size: 14px'>{$info['orderNo']}</div></div>
                      <div class='printSubTitle'>生产派工单</div>
                 </div>
                 <div class='table-top-title'>
                     <ul>
                        <li>生产部门：{$line['workshop']}-{$line['name']}</li> <li>班组：{$team['name']}</li>
                     </ul>
                      <ul>
                         <li>工序：{$process['name']}</li><li>计划加工时间：{$info['startDate']} 至 {$info['endDate']}</li>
                     </ul>
                      <ul>
                        <li>&nbsp;</li>
                     </ul>
                     <ul>
                        <li style='font-weight: bold'>产品：{$material['code']}-{$material['name']}</li>
                     </ul>
                     <ul>
                       <li>规格型号：{$material['model']}</li><li>数量：" . self::lostZero($info['num'], 'numPrecision') . "</li>
                    </ul>
                     <ul> <li>源单类型：{$sourceOrderType}</li><li>关联源单：{$machiningOrder['orderNo']}</li></ul>
                    <ul> <li>备注：{$info['text']}</li></ul>
                    
                      <div style='margin-top: 10px'>
                           <img alt='二维码' style='width: 100px;vertical-align: top' src='$url'>
                           <div class='footer-ul-parent'>
                           <ul class='footer-ul'>
                               <li>打印时间：" . date('Y/m/d H:i') . "</li>
                               <li>制单人：" . self::findStaff($info['stid']) . "</li>
                               <li></li>
                           </ul>
                           </div>
                         </div>
                 </div>
            ";
		}
		$html  = <<<eof
                    <div id="content-box" style="display: none">
                    
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$content}
                    </div>
                 
eof;
		$html  .= $this->style();
		$print = new printClass();

		return $print->showPrint($html, 'landscape', ['pageSize' => 'A5']);
	}

	/**
	 * 打印
	 */
	public function printPage(): string
	{
		$info        = query(self::table, " id = '{$this->get('id')}'");
		$material    = query('material', "id = '$info[materialId]'");
		$company     = query('company', "coid = '" . self::$coid . "'");//公司名称
		$process     = query('process', "id = '$info[processId]'");
		$line        = query('product_line', "id = '$info[lineId]'");
		//二维码
		$url             = root . 'pay/wxpay/wxScanPng.php?url=' . urlencode("source=machining_send_order&id=" . $info['id']);
		$machiningOrder  = query('machining_order', "id = '$info[machiningOrderId]'");
		$sourceOrderType = $machiningOrder['orderType'] == '生产计划' ? '生产计划单' : '半成品加工单';
		$team            = query('team', "id = '$info[teamId]'");
		$divHtml         = "
                 <div>
                      <div class='printTitle' style='font-weight: bold;position: relative'>{$company['name']} <div style='position: absolute;font-weight: normal;right: 10px;top: 0;font-size: 14px'>{$info['orderNo']}</div></div>
                      <div class='printSubTitle'>生产派工单</div>
                 </div>
                 <div class='table-top-title'>
                     <ul>
                        <li>生产部门：{$line['workshop']}-{$line['name']}</li> <li>班组：{$team['name']}</li>
                     </ul>
                      <ul>
                         <li>工序：{$process['name']}</li><li>计划加工时间：{$info['startDate']} 至 {$info['endDate']}</li>
                     </ul>
                       <ul>
                        <li>&nbsp;</li>
                     </ul>
                     <ul>
                        <li style='font-weight: bold'>产品：{$material['code']}-{$material['name']}</li>
                     </ul>
                     <ul>
                       <li>规格型号：{$material['model']}</li><li>数量：" . self::lostZero($info['num'], 'numPrecision') . "</li>
                    </ul>
                     <ul> <li>源单类型：{$sourceOrderType}</li><li>关联源单：{$machiningOrder['orderNo']}</li></ul>
                    <ul> <li>备注：{$info['text']}</li></ul>
                    
                      <div style='margin-top: 10px'>
                           <img alt='二维码' style='width: 100px;vertical-align: top' src='$url'>
                           <div class='footer-ul-parent'>
                           <ul class='footer-ul'>
                               <li>打印时间：" . date('Y/m/d H:i') . "</li>
                               <li>制单人：" . self::findStaff($info['stid']) . "</li>
                               <li></li>
                           </ul>
                           </div>
                         </div>
                 </div>
            ";
		$html            = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$divHtml}
                    </div>
                 
eof;
		$html            .= $this->style();
		$print           = new printClass();

		return $print->showPrint($html, 'landscape', ['pageSize' => 'A5']);
	}

	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '已确认',
			'checkId'     => self::$stid,
			'confirmTime' => $this->time,
		];

		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此' . self::title;
		} elseif ($info['state'] != '待确认') {
			$json['warn'] = '此' . self::title . '不是待确认状态，不能确认';
		} else {
			$this->startTrans();
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();
				auditClass::operateRecord($info['id'], '生产派工单', '确认');
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = '确认成功';
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			} else {
				$this->rollback();
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 撤回
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '草稿',
			'checkId'     => '',
			'confirmTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有撤回权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此生产派工单';
		} elseif ($info['state'] != '已确认') {
			$json['warn'] = '此生产派工单不是已确认状态，无需撤回';
		} elseif (static::total(array('table' => 'process_report', "where" => "sendId = '$info[id]' and coid = '" . self::$coid . "'")) > 0) {
			$json['warn'] = '此生产派工单已关联有工序报工的单据，不能撤回';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditClass::operateRecord($info['id'], '生产派工单', '撤回');
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = '撤回成功';
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 提交
	 */
	public function commitEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state' => '待确认',
		];
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此生产派工单';
		} elseif ($info['state'] != '草稿') {
			$json['warn'] = '此生产派工单不是草稿状态，不能提交';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditClass::operateRecord($info['id'], '生产派工单', '提交');
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = '提交成功';
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $power = $word = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否已确认此' . self::title . '，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此' . self::title . '？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认撤回此' . self::title . '？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * 批量添加标签
	 */
	public function batchAddTags(): bool|string
	{
		$formName    = $this->post('formName');
		$label_group = find(array('table' => 'tag', 'where' => "type=2 and coid = '" . self::$coid . "' order by time asc"));
		$group_li    = '';
		foreach ($label_group['array'] as $array) {
			$group_li     .= "<li>{$array['name']}</li><li>";
			$detail_ul    = <<<eof
<ul class="label-content-sec-ul client-level">
eof;
			$label_detail = find(array('table' => 'tag_detail', 'where' => "orderId = '$array[id]' order by list asc"));
			foreach ($label_detail['array'] as $value) {
				$detail_ul .= "<li class='background-color-gray' data-id='{$value['id']}'>{$value['name']}</li>";
			}
			$group_li .= "{$detail_ul}<input name='tagMxId[]' type='hidden' value=''></ul></li>";
		}

		$html = <<<efo
<form name="labelForm">
<div class="label-content">
<ul>
     {$group_li}
</ul>
</div>
<div class="label-footer">
     已选<span id="label-num">0</span>个<span class="del-row-button" id="reset" style="margin-left: 20px">重置</span>
     <span class="spanButton" onclick="$('#machiningSendOrderBatchAddTags').hide()" style="float: right">取消</span>
     <span class="spanButton li-btn-blue-bg" onclick="confirm_batch()" style="float: right">确认</span>
</div>
</form>
<style>
.label-content{
   margin: 10px 20px;height: 570px;border-bottom: 2px dashed rgb(215, 215, 215);
}
.label-content-sec-ul li {
  float: left;margin: 10px 5px;text-align: center;cursor: pointer;
}
.background-color-gray{
  margin-left: 0;
}
.label-content>ul>li{
  display: flex;
}
.label-content>ul>li:nth-child(2n+1){
  padding-left: 5px;
  margin-top: 5px;
}
.label-footer{
  height: 50px;
  line-height: 50px;
  margin: 0 20px;
}
</style>
<script>
function confirm_batch(){
     let serialize = $("[name='labelForm']").serialize();
     serialize+='&'+$("[name='{$formName}']").serialize();
    $('#machiningSendOrderBatchAddTags').hide()
     $.post(root+'control/adIndex.html?cla=machiningSendOrder&fun=batchAddTagsEdit', serialize, function (data) {
         if (data.warn == 2) {
            if (data.href) {
              window.location.href = data.href;
            }else if ($("#renovate").attr("url")) {
                        //页卡切换时会保存菜单关键字在renovate的url中
                        window.location.href = $("#renovate").attr("url");
             }  else {
              window.location.reload();
            }
          } else {
            warn(data.warn);
          }
    }, "json");
}
//计算标签数量
 function set_label_num(){
    let num =  $(".label-content-sec-ul .background-color-blue").length;
    $("#label-num").html(num);
 }
 //点击标签
 $(".label-content-sec-ul li").on('click',function() {
     let parent = $(this).parent();
     if ($(this).hasClass('background-color-blue')){
          parent.find("li").removeClass('background-color-blue');
          $(this).siblings("input[name='tagMxId[]']").val('');
     }else{
         parent.find("li").removeClass('background-color-blue');
         $(this).addClass('background-color-blue');
         let id = $(this).data('id');
         $(this).siblings("input[name='tagMxId[]']").val(id);
     }
   
     set_label_num();
 })
 //重置标签
 $("#reset").on('click',function (){
     $(".label-content-sec-ul").find("li").removeClass('background-color-blue');
     $(".label-content-sec-ul").find("input[type='hidden']").val('');
     set_label_num();
 })
</script>
efo;

		return $this->layer(array("title" => "批量添加标签", "height" => 700, "width" => 900, "html" => $html));
	}

	/**
	 * 批量添加标签编辑
	 */
	public function batchAddTagsEdit(): bool|string
	{
		$listId  = $this->post('listId');
		$tagMxId = $this->post('tagMxId');//标签ID
		if (empty($listId) || !is_array($listId)) {
			$json['warn'] = '您还没有选择单据';
		} elseif (empty($tagMxId) || !is_array($tagMxId)) {
			$json['warn'] = '您还没有选择标签';
		} else {
			$x    = 0;
			$text = '';
			foreach ($listId as $id) {
				$machiningSendOrder = query(self::table, "id = '$id'");
				$x++;
				$tagsText = '';
				//添加标签
				$kehu_label_id = [];
				foreach ($tagMxId as $tagsId) {
					$tags_detail = query('tag_detail', "id = '$tagsId'");
					if ($tags_detail['id']) {
						$kehu_label = query('kehu_label', "targetId = '$machiningSendOrder[id]' and tag_detail_id = '$tagsId'");
						$tags       = query('tag', "id = '$tags_detail[orderId]'");
						$tagsText   .= $tags_detail['name'] . ',';
						if (empty($kehu_label['id'])) {
							$mid             = self::getId();
							$kehu_label_id[] = $mid;
							static::insert(array(
								'table' => 'kehu_label',
								'field' => [
									'id'            => $mid,
									'coid'          => self::$coid,
									'targetId'      => $machiningSendOrder['id'],
									'tag_detail_id' => $tagsId,
									'tagId'         => $tags['id'],
									'type'          => 2,
								],
							));
						} else {
							$kehu_label_id[] = $kehu_label['id'];
						}
					}
				}
				//删除无效关联的标签
				delete(array('table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehu_label_id) . "') and targetId = '$machiningSendOrder[id]'"));
				update(array('table' => self::table, 'field' => ['tags' => $tagsText], 'where' => "id = '$machiningSendOrder[id]'"));
				$text .= "生产派工单【{$machiningSendOrder['orderNo']}】添加了标签{$tagsText}<br>";
			}
			$this->logText(["type" => self::page, "text" => $this->control['name'] . "批量给生产派工单添加标签：" . $text]);
			$json['warn']     = 2;
			$_SESSION['warn'] = '成功给' . $x . '个生产派工单添加了标签';
		}
		return json_encode($json, 320);
	}

    public function confirmed()
    {
        $json['html'] = $this->homeForm('已确认');
        return json_encode($json, 320);
    }

    public function confirmedSearch()
    {
        //全等查询数组
        $equal = array(
            'coid'      => self::$coid,
            "type"      => $this->post('type'),
            "processId" => $this->post('processId'),
            "lineId"    => $this->post('lineId'),
            'classify'  => '生产派工',
            'state'     => '已确认',
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );

        //初始化
        $and  = "";
        $mAnd = '';

        if ($this->post('machiningOrderNo')) {
            $and = " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
        }
        if ($this->post('code')) {
            $mAnd .= " and code like '%" . $this->post('code') . "%'";
        }
        if ($this->post('materialName')) {
            $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($mAnd) {
            $and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'startDate');
        }
        if ($this->post('endTime')) {
            $and .= self::timeComparison($this->post('endTime'), field: 'endDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page  = $this->page(array("table" => self::table, "where" => $where, "order" => "recordDate desc,orderNo desc"));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取表头
        $tr[]     = array('', '单据编号', "加工单类型", '单据标签', "生产线", "工序", '班组', "物料编码", "物料名称", "规格型号", '单位', '派工数量', '已报工数量', '关联设备','源单类型', '关联源单', '计划开工日期', '计划完成日期', '单据日期', '状态');
        $url      = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=生产派工单&id=" . $array['id'] . "')"),
            );

            $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
            $line           = query('product_line', "id = '$array[lineId]'");
            $process        = query('process', "id = '$array[processId]'");
            $material       = query('material', "id = '$array[materialId]'");
            $tags           = orderTagClass::getTagName($array['id']);
            $team           = query('team', "id = '$array[teamId]'");
            $closeSign      = $array['isClose'] ? "<span class='no-choose'></span>" : '';//关闭单据颜色显示标志
            //报工数量
            $reportNum = find(array('table' => 'process_report', 'where' => "sendId ='$array[id]' and processId = '$array[processId]' and state = '已确认'", 'sum' => "yield"));
            //返回本行
            $tr[] = array(
                $this->dominate($dominate) . $closeSign, $array['orderNo'], $array['type'], $tags, $line['workshop'] . '-' . $line['name'], $process['name'], $team['name'], $material['code'], $material['name'], $material['model'], $array['unit'],
                self::lostZero($array['num'], 'numPrecision'), self::lostZero($reportNum, 'numPrecision'),equipmentClass::getName($array['deviceId']), $this->orderTypeOption[$array['orderType']], $machiningOrder['orderNo'], $array['startDate'], $array['endDate'], $array['recordDate'], $array['state'],
            );
        }
        //控件
        $button = "";
        $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        //合计
        $total = find(array(
            "table"=>self::table,
            "field"=>" id,num ",
            "where"=>$where
        ));
        $ids = implode("','",(array)array_column($total['array'],'id'));
        $planNum = array_sum((array)array_column($total['array'],'num'));
        $reportNum = find(array('table' => 'process_report', 'where' => "sendId in ('$ids') and state = '已确认'", 'sum' => "yield"));
        $completionRate = $planNum>0?round($reportNum/$planNum,2)*100:0;
        $button.=saleIncomeClass::titleSpan('派工数量（计划产量）',self::lostZero($planNum, 'numPrecision'));
        $button.=saleIncomeClass::titleSpan('报工数量（完成产量）',self::lostZero($reportNum, 'numPrecision'));
        $button.=saleIncomeClass::titleSpan('完成率',$completionRate.'%');
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='reportedForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . machiningOrderClass::closeJs() . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 导出
     */
    public function exportData()
    {
        $tr     = [];
        $sql    = $_SESSION[self::page]['sql'];
        $title  = array('单据编号', "加工单类型", '单据标签', "生产线", "工序", '班组', "物料编码", "物料名称", "规格型号", '单位', '派工数量', '已报工数量', '关联设备', '源单类型', '关联源单', '计划开工日期', '计划完成日期', '单据日期', '状态');
        $result = sqlFind($sql);
        if (is_array($result)) {
            foreach ($result as $array) {
                $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
                $line           = query('product_line', "id = '$array[lineId]'");
                $process        = query('process', "id = '$array[processId]'");
                $material       = query('material', "id = '$array[materialId]'");
                $tags           = orderTagClass::getTagName($array['id']);
                $team           = query('team', "id = '$array[teamId]'");
                //报工数量
                $reportNum = find(array(
                    'table' => 'process_report',
                    'where' => "sendId ='$array[id]' and processId = '$array[processId]' and state = '已确认'",
                    'sum' => "yield"
                ));
                //返回本行
                $tr[] = array($array['orderNo'], $array['type'], $tags, $line['workshop'] . '-' . $line['name'], $process['name'], $team['name'], $material['code'], $material['name'], $material['model'], $array['unit'],
                    self::lostZero($array['num'], 'numPrecision'), self::lostZero($reportNum, 'numPrecision'), equipmentClass::getName($array['deviceId']), $this->orderTypeOption[$array['orderType']], $machiningOrder['orderNo'], $array['startDate'], $array['endDate'], $array['recordDate'], $array['state'],
                );
            }
        }
        $text = $this->control['name'] . "导出了" . self::title;
        $this->logText(["type" => self::page, "text" => $text]);
        $this->excelOut($title, $tr, self::title . ".xlsx");
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}
